// **********************************************************************************************
// Este archivo fuente es propiedad de Feria de Remates S.R.L. de C.V. de C.V. Prohibida su copia 
// o uso sin autorización explícita.
// This source file is propietary to Feria de Remates. May not be used or copied
// without explicit authorization.
// **********************************************************************************************/
package com.feriaderemates.dao.user;

import com.feriaderemates.domain.userAccount.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

/**
 * 
 * Singleton Dao class. Implements user operations.
 *
 * @author Oscar Garcia
 */
@Slf4j
@Service("userDao")
public class UserDao extends JdbcDaoSupport implements UserDaoInterface {
    //getting the datasouercs
    private DataSource dataSource;
    
    private static final UserDao userDao = new UserDao();
    // Querys
    private static String INSERT_USER = "INSERT INTO fdr.user (first_name, last_name, hashed_password, user_account_status, username, "
            + " user_account_type, registration_confirmation_code, registration_date) "
            + " VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";

    private static String GET_USER_BY_USERNAME= "Select * from fdr.user where username  = ?";
    
    /**
     * Factory method.
     * 
     * @return the only one instance of this class
     */
    static UserDao getInstance() {
        return userDao;
    }

    private UserDao() {
    }

    public int registerUser(final User user, final String registrationConfirmationCode) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(INSERT_USER, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, user.getFirstName());
                ps.setString(2, user.getLastName());
                ps.setString(3, user.getHashedPassword());
                ps.setString(4, user.getUserAccountStatus().name());
                ps.setString(5, user.getUsername());
                ps.setString(6, user.getAccountType().name());
                ps.setString(7, registrationConfirmationCode);
                return ps;
            }
        }, keyHolder);
        Object key = keyHolder.getKeys().get("user_id");
        return (Integer) key;
    }
    
    // work office
    
    public String findFirstNameById(Long id) {
        String firstName = jdbcTemplate.queryForObject(
            "select first_name from contact where id = ?",
            new Object[]{id}, String.class);
        return firstName;
        Object[] args = {username};
        
        User user = this.getJdbcTemplate().queryForObject(GET_USER_BY_USERNAME,args,User.class);
        
        
        String sql = "SELECT * FROM user";
    	List<User> customers = null;
    	 try{
    	 customers  = getJdbcTemplate().query(sql,new BeanPropertyRowMapper(User.class));
    	 }catch(Exception e){
    		 e.printStackTrace();
    	 }
            return customers.get(0);
        
        
    }
    //end

    public User getUserByUsername(String username) {
    
    
    
   
        Object[] args = {username};
        
        List userList =  this.getJdbcTemplate().query(GET_USER_BY_USERNAME,args, new ParameterizedRowMapper<User>(){  
            public User mapRow(ResultSet rs, int rowNum)  throws SQLException {  
                return  new User(
                    rs.getInt("user_id"),
                    rs.getString("first_name"),
                    rs.getString("last_name"),
                    rs.getString("second_last_name"),
                    rs.getString("username"),
                    rs.getString("email"),
                    rs.getString("hashed_password")
                ); 
            }  
        });  
        User user = null;
        user = (User)userList.get(0);
       return user;
          
    }

    public User getUserByEmail(String email) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void updateUser(User user) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void updateUserPassword(String newPassword, String recoveryCode) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Timestamp getLastTimeUserRequestedResetPassword(String email) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void setUsersRecoveryCode(String email, String recoveryCode) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
};
